/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.celiosilva.simbanc.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author celio@celiosilva.com
 */
public class GravadorSerial<T> {

    private final               File                file;

    public GravadorSerial(File diretorio, String nomeArquivo) {
        diretorio.mkdirs();
        file = new File(diretorio, nomeArquivo);
    }

    public T gravarEmArquivo(T dados) throws IOException{
        this.serializarObjeto(dados);
        return dados;
    }    

    private void serializarObjeto(Object o) throws IOException{
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        try {
            oos.writeObject(o);
            oos.flush();
        } finally {
            if (oos != null)
                oos.close();
        }
    }

    public T lerDoArquivo() throws IOException, ClassNotFoundException{
        return (T) this.deserealizarObjeto();
    }

    private Object deserealizarObjeto() throws IOException, ClassNotFoundException{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        try {
            return ois.readObject();
        } finally {
            ois.close();
        }
    }

}
